package com.zwc.kotlin.coroutines.core

sealed class CoroutineState {
    private var disposableList: Disposablelist = Disposablelist.Nil
    fun from(state: CoroutineState): CoroutineState {
        this.disposableList = state.disposableList
        return this
    }

    fun with(disposable: Disposable): CoroutineState {
        this.disposableList = Disposablelist.Cons(disposable, this.disposableList)
        return this
    }

    fun without(disposable: Disposable): CoroutineState {
        this.disposableList = this.disposableList.remove(disposable)
        return this
    }

    fun <T> notifyCompletion(result: Result<T>) {
        this.disposableList.loopOn<CompletionHandlerDisposable<T>> {
            it.onComplete(result)
        }
    }

    fun notifyCancellation() {
        disposableList.loopOn<CancellationHandlerDisposable> {
            it.onCancel()
        }
    }

    fun clear() {
        this.disposableList = Disposablelist.Nil
    }

    /**
     * 协程启动后 即进入该状态，直到完成或者被取消
     */
    class Incomplete : CoroutineState()

    /**
     * 协程执行中被取消后进入该状态
     */
    class Cancelling : CoroutineState()

    /**
     * 协程执行完成（包括正常返回和异常结束）时进入该状态
     */
    class Complete<T>(val value: T? = null, val exception: Throwable? = null) : CoroutineState()

}

